package cn.lishiyuan.algorithm.stack;

import java.util.Arrays;

/**
 * 使用数组结构实现的栈，自动扩容（其实是不合理的），不会缩容
 * @param <T>
 */
public class ArrayStack<T> implements LeeStack<T>{

    private Object[] array;

    /**
     * 当前位置
     */
    private int count = 0;

    public ArrayStack(int size){
        if (size <= 0) {
            throw new IllegalArgumentException();
        }
        array = new Object[size];
    }

    public int count(){
        return count;
    }

    @Override
    public boolean isEmpty() {
        return count == 0;
    }

    @Override
    public void push(T data) {
        // 达到最大值
        if(count == array.length){
            // 扩容
            Object[] newArray = new Object[array.length * 2];
            System.arraycopy(array, 0, newArray, 0, array.length);
            array = newArray;
        }
        array[count] = data;
        count++;
    }

    @Override
    public T pop() {
        if(count == 0){
            return null;
        }
        count--;
        T result = (T) array[count];
        array[count] = null;
        return result;
    }

    @Override
    public T peek() {
        if(count == 0){
            return null;
        }
        T result = (T) array[count-1];
        return result;
    }

    @Override
    public String toString() {
        return Arrays.toString( Arrays.copyOf(array, count));
    }
}


